package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MapDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service(interfaceClass = MapService.class)
@Transactional
public class MapServiceImpl implements MapService {

    @Autowired
    private MapDao mapDao;

    //查询地图上所有的点
    @Override
    public List<Map> findMap() {
        List<Map> lsit = mapDao.findMap();
        return lsit;
    }

    //分页查询
    public PageResult findPage(QueryPageBean pageBean) {
        Integer currentPage = pageBean.getCurrentPage();
        Integer pageSize = pageBean.getPageSize();
        String queryString = pageBean.getQueryString();

        //如果条件不为空和空字符串 那么查询的页数为1
        if (queryString != null && !"".equals(queryString)) {
            currentPage = 1;
        }
        //使用分页助手插件实现分页查询
        PageHelper.startPage(currentPage, pageSize);
        Page<Map> page = mapDao.findAll(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }


    //根据id删除检查项
    public void delete(String address) {
        long count = mapDao.selectCountByMapAddress(address);
        System.out.println(count);
        if (count > 0) {
            //已经被关联，不能删除
            throw new RuntimeException(MessageConstant.DELETE_ADDRESS_FAIL);
        } else {
            //可以删除
            mapDao.deleteByAddress(address);
        }
    }

    //添加公司地址
    @Override
    public void addAddress(Map map) {
        if ("".equals(map.getAddress())) {
            throw new RuntimeException(MessageConstant.ADD_ADDRESS_NOTNULL);
        } else if ("".equals(map.getLatitude()) || "".equals(map.getLongitude())) {
            throw new RuntimeException(MessageConstant.ADD_LATANDLONG_NOTNULL);
        }
        mapDao.addAddress(map);
    }
}
